#!/usr/bin/python3

from xml.dom.minidom import parse
import xml.dom.minidom as xmldom

# 使用minidom解析器打开 XML 文档
DOMTree = xmldom.parse("D:\\tmp\\target_regionInfo.xml")
print("xmldom.parse:", type(DOMTree))
elementobj = DOMTree.documentElement
print("get element object:", type(elementobj))
# get sub label
subElementObj = elementobj.getElementsByTagName("targeting")
print("getElementsByTagName:", type(subElementObj))
print(len(subElementObj))

# get tab attribute
print('{}\t{}'.format(subElementObj[0].getAttribute("name"), subElementObj[0].getAttribute("value")))
"""
{洲}{国家}{省}{城市}
洲：101
国家 特殊值000-洲；001-Other
省   特殊值000-国家
城市  特殊值0000-省
示例：
1010230010001  （101-023-001-0001）(亚洲-MY-吉隆坡联邦直辖区-吉隆坡)
nation
"""
area_dict = {}
with open('target_regionInfo.txt', 'w') as fw:
    # fw.write('{}\t{}\n'.format('target_id', 'nation'))
    for i in range(len(subElementObj)):
        # print('{}\t{}\t{}'.format(i, subElementObj[i].getAttribute("value"), subElementObj[i].getAttribute("code")))
        nation = subElementObj[i].getAttribute("code")
        target_id = subElementObj[i].getAttribute("value")
        if nation is None or len(nation) != 2:
            continue
        fw.write('{}\t{}\n'.format(target_id[0:6], nation))
